<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms;
use app\common\model\ExpertMoneyLog;
use think\Db;
use think\Exception;

/**
 * 搭子处理相关接口
 */
class Playmate extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 测试方法
     */
    public function test()
    {
        //模拟登录
        $this->auth->direct(2);
        $res = $this->auth->getUserinfo();
        $this->success('返回成功', $res);
    }


    /**
     * 申请成为达人(已提交过申请则为修改)
     * @param string $living_photos 生活照(多张逗号隔开) 如'https://bxsh-upload.oss-cn-fuzhou.aliyuncs.com/uploads/20250506/844bc7abf52d3c5d5d8a8af07773e544.jpg, https://bxsh-upload.oss-cn-fuzhou.aliyuncs.com/uploads/20250509/f66487dafd1a0c7ae0a0360a13ca93c7.jpg'
     * @param string $name 姓名
     * @param int $gender 性别
     * @param int $mobile 手机号
     * @param int $captcha 手机验证码 验证码发送接口在sms中的send
     * @param int $city_id 意向城市id
     */
    public function applyTobePlaymate()
    {
        $user_id = $this->auth->id;

        $living_photos = $this->request->post('living_photos', 'https://bxsh-upload.oss-cn-fuzhou.aliyuncs.com/uploads/20250506/844bc7abf52d3c5d5d8a8af07773e544.jpg, https://bxsh-upload.oss-cn-fuzhou.aliyuncs.com/uploads/20250509/f66487dafd1a0c7ae0a0360a13ca93c7.jpg');
        $name = $this->request->post('name', '用户'.rand(100000,999999));
        $gender = $this->request->post('gender', 1);
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $city_id = $this->request->post('city_id');
        if(!preg_match('/^1[3-9]\d{9}$/', $mobile)) $this->error('联系人手机号格式有误');
        if(empty($city_id)) $this->error('请选择意向城市');
        $cityInfo = db('city')->where('id', $city_id)->field('id')->find();
        if(empty($cityInfo)) $this->error('意向城市不存在，请重新选择');

        $ret = Sms::check($mobile, $captcha, 'playmateapply');//验证码发送事件 如register=注册，changemobile=修改手机号，playmateapply=申请成为搭子
        if (!$ret) $this->error(__('验证码不正确'));

        $where = [];
        $where['user_id'] = $user_id;
        $expertInfo = db('expert')->where($where)->find();
        $nowTime = time();
        if(!empty($expertInfo)){
            if(in_array($expertInfo['status'], [0,1,3])) $this->error('已存在您的搭子申请信息，无需再次发起申请');
            //申请过 未通过 则修改
            $data = [
                'images' => $living_photos,
                'name' => $name,
                'gender' => $gender,
                'mobile' => $mobile,
                'city_id' => $city_id,
                'status' => 0,
                'updatetime' => $nowTime
            ];
            $res = db('expert')->where('user_id', $user_id)->update($data);
        }else{
            //创建一条搭子申请单
            $data = [
                'user_id' => $user_id,
                'images' => $living_photos,
                'name' => $name,
                'gender' => $gender,
                'mobile' => $mobile,
                'city_id' => $city_id,
                'status' => 0,
                'createtime' => $nowTime
            ];
            $res = db('expert')->insert($data);
        }

        if($res) $this->success('已提交申请，请等待审核');
        else $this->error('申请提交失败，请重新操作');
    }

    /**
     * 获取当前"达人申请"状态
     */
    public function getPlaymateStatus()
    {
        $user_id = $this->auth->id;
        $where = [];
        $where['user_id'] = $user_id;
        $expertInfo = db('expert')->where($where)->field('user_id,status')->find();
        $this->success('ok', $expertInfo);
    }

    /**
     * 完善达人信息
     * @param string $name Y 姓名
     * @param int $gender Y 性别:1=男,2=女
     * @param string $birthday Y 生日:格式如2000-10-01
     * @param string $id_number Y 身份证号
     * @param string $height Y 身高(cm)
     * @param string $weight Y 体重(kg)
     * @param string $label_ids Y 标签:格式如1,2,3
     * @param string $qualification_id Y 学历:格式如1
     * @param int $job_year Y 从业年份:格式如1
     * @param int $city_id Y 意向城市id:格式如1
     * @param string $now_address Y 所在地址
     * @param string $lat Y 经度:如24.484503
     * @param string $lng Y 维度:如118.032818
     * @param string $content Y 达人简介
     * @param string $avatar Y 头像
     * @param string $living_photos Y 生活照(多张逗号隔开) 如'https://bxsh-upload.oss-cn-fuzhou.aliyuncs.com/uploads/20250506/844bc7abf52d3c5d5d8a8af07773e544.jpg, https://bxsh-upload.oss-cn-fuzhou.aliyuncs.com/uploads/20250509/f66487dafd1a0c7ae0a0360a13ca93c7.jpg'
     * @param string $video N 主页视频
     * @param string $wx_number N 微信号
     */
    public function completePlaymateInfo()
    {
        $user_id = $this->auth->id;
        $inputParam = $this->request->post();

        $requireFieldRule = [
            'name' => 'require',
            'gender' => 'require',
            'birthday' => 'require',
            'id_number' => 'require',
            "height" => 'require',
            'weight' => 'require',
            'label_ids' => 'require',
            'qualification_id' => 'require',
            'job_year' => 'require',
            'city_id' => 'require',
            'now_address' => 'require',
            'lat' => 'require',
            'lng' => 'require',
            'content' => 'require',
            'avatar' => 'require',
            'living_photos' => 'require'
            //'contact_mobile_no' => 'require|regex:/^1[3-9]\d{9}$/'
        ];
        $requiredFieldMsg = [
            'name' => '姓名不能为空',
            'gender' => '性别不能为空',
            'birthday.require' => '生日不能为空',
            'id_number.require' => '身份证号不能为空',
            'height.require' => '身高不能为空',
            'weight.require' => '体重不能为空',
            'label_ids.require' => '标签不能为空',
            'qualification_id.require' => '学历不能为空',
            'job_year.require' => '从业年限不能为空',
            'city_id.require' => '意向城市不能为空',
            'now_address.require' => '所在地址不能为空',
            'lat.require' => '经度不能为空',
            'lng.require' => '纬度不能为空',
            'content.require' => '达人简介不能为空',
            'avatar.require' => '头像不能为空',
            'living_photos.require' => '生活照不能为空'
            //'contact_mobile_no.regex' => '联系人手机号格式有误',
        ];

        $validate = new \think\Validate($requireFieldRule, $requiredFieldMsg);
        $validResult = $validate->check($inputParam);
        if(!$validResult){
            $this->error($validate->getError());
        }

        //将接收的参数转为变量
        extract($inputParam);

        //处理下非必填参数
        $wx_number = $wx_number?? '';
        $video = $video?? '';

        $cityInfo = db('city')->where('id', $city_id)->field('id')->find();
        if(empty($cityInfo)) $this->error('意向城市不存在，请重新选择');
        //只有审核通过的达人才能修改完善资料
        $status = db('expert')->where('user_id', $user_id)->value('status');
        if(!in_array($status, [1,3])) $this->error('您的达人状态不符合，不能进行修改');

        //执行修改完善资料 并 将status改为3
        $data = [
            'name' => $name,
            'gender' => $gender,
            'birthday' => $birthday,
            'id_number' => $id_number,
            'height' => $height,
            'weight' => $weight,
            'label_ids' => $label_ids,
            'qualification_id' => $qualification_id,
            'job_year' => $job_year,
            'city_id' => $city_id,
            'now_address' => $now_address,
            'lat' => $lat,
            'lng' => $lng,
            'content' => $content,
            'image' => $avatar,
            'images' => $living_photos,
            'wx_number' => $wx_number,
            'video' => $video,
            'status' => 3
        ];
        $res = db('expert')->where('user_id', $user_id)->update($data);
        if($res === false) $this->error('系统执行异常!');
        $this->success('ok');
    }



    /**
     * 获取达人详情
     */
    public function getPlaymateInfo()
    {
        $user_id = $this->auth->id;
        $where = [];
        $where['user_id'] = $user_id;
        $expertInfo = db('expert')->where($where)->field('user_id,status,images,images,name,order_status,all_money,money')->find();
        $this->success('ok', $expertInfo);
    }



    /**
     * 首页今日统计
     */
    public function getPlaymateTodayCount()
    {
        $user_id = $this->auth->id;
        $where = [];
        $where['service_date'] = date("Y-m-d");
        $where['expert_user_id'] = $user_id;
        $where['status'] = ['<>','-1'];
        $expertInfo = db('service_order')->where($where)->field('real_price,price,status')->select(); //今日订单

        $waiting_service_num = db('service_order')->where(['expert_user_id' => $user_id ,'status' => 2])->count(); //待服务

        $today_money = $today_num  = $evaluate_num = 0; // 今日业绩  今日订单  待服务  待评价

        if ($expertInfo){
            foreach ($expertInfo as $value){
                if ($value['status'] == 6) {
                    $today_money += $value['price'];
                    $today_num ++;
                }
            }
        }
        $data = [
            'today_money' => $today_money,
            'today_num' => $today_num,
            'waiting_service_num' => $waiting_service_num,
            'evaluate_num' => $evaluate_num,
            ];

        $this->success('ok', $data);
    }


    /**
     * 首页近六个月统计
     */
    public function getPlaymateMonthCount()
    {

        $user_id = $this->auth->id;

        $t = strtotime("-5 month");
        $lastDay = date('Y-m-',$t).'1'; //5个月前日期

        $where = [];
        $where['service_date'] = ['>=', $lastDay];
        $where['expert_user_id'] = $user_id;
        $where['status'] = 6;
        $expertInfo = db('service_order')->where($where)->field('count(id) as count_num, MONTH(service_date) service_month')->group('MONTH(service_date)')->select(); //订单统计


        // 获取近 6个月 月份
        for($i = 0; $i <= 5; ++$i){
            $t = strtotime("-$i month");
            $month = date('m',$t);
            $data[$month] = 0;
            foreach ($expertInfo as $value){
                if (sprintf("%02d", $value['service_month']) == $month){
                    $data[sprintf("%02d", $value['service_month'])] = $value['count_num'];;
                }
            }
        }

        $this->success('ok', $data);
    }



    /**
     * 设置 达人 当前位置
     * @param string now_address Y 所在地址
     * @param string now_lng Y 经度:如24.484503
     * @param string now_lat Y 维度:如118.032818
     */
    public function setPlaymateAddress()
    {
        $user_id = $this->auth->id;
        $inputParam = $this->request->post();

        $requireFieldRule = [
            'now_address' => 'require',
            'now_lng' => 'require',
            'now_lat' => 'require',
        ];
        $requiredFieldMsg = [
            'now_address.require' => '所在地址不能为空',
            'now_lng.require' => '经度不能为空',
            'now_lat.require' => '纬度不能为空',
        ];

        $validate = new \think\Validate($requireFieldRule, $requiredFieldMsg);
        $validResult = $validate->check($inputParam);
        if(!$validResult){
            $this->error($validate->getError());
        }

        //将接收的参数转为变量
        extract($inputParam);

        //执行修改完善资料 并 将status改为3
        $data = [
            'now_address' => $now_address,
            'now_lat' => $now_lat,
            'now_lng' => $now_lng,
        ];
        $res = db('expert')->where('user_id', $user_id)->update($data);
        if($res === false) $this->error('系统执行异常!');
        $this->success('ok');
    }


    /**
     * 申请提现
     * @param string money Y 提现金额
     * @param string bank_type Y 提现方式
     */
    public function applyPlaymateWithdrawal()
    {
        $user_id = $this->auth->id;
        $money = $this->request->post('money');
        $bank_type = $this->request->post('bank_type');

        if (!$money || !is_numeric($money)){
            $this->error('参数错误!');
        }
        if (!in_array($bank_type, [1,2])){
            $this->error('参数错误!');
        }

        //查询达人信息
        $where = [];
        $where['user_id'] = $user_id;
        $expertInfo = db('expert')->where($where)->field('id,money')->find();
        if (!$expertInfo){
            $this->error('参数错误!');
        }
        if ($expertInfo['money'] < $money){
            $this->error('余额不足!');
        }

        Db::startTrans();
        try {
            //提现记录
            $data = [
                'type' => 2,
                'user_id' => $user_id,
                'money' => round($money,2),
                'bank_type' => $bank_type,
                'status' => 0,
                'createtime' => time(),
            ];
            $withdrawal = db('withdrawal')->insert($data);

            //余额记录
            $log = [
                'expert_id' => $expertInfo['id'],
                'user_id' => $user_id,
                'type' => 2,
                'from_user_id' => $user_id,
                'from_order_id' => $withdrawal,
                'money' => round($money,2),
                'before' => $expertInfo['money'],
                'after' => round($expertInfo['money']- round($money,2),2),
                'createtime' => time()
            ];
            db('expert_money_log')->insert($log);

            //扣除余额
            db('expert')->where(['user_id'=>$user_id])->setDec('money', round($money,2));

            Db::commit();
        } catch (Exception $e) {
            //print_r($e->getMessage());
            Db::rollback();
            $this->error('系统执行异常!');
        }
        $this->success('ok');
    }




    /**
     * 达人 设置服务
     * @param string service_id Y 服务id
     * @param string price Y 服务价格
     */
    public function setPlaymateService()
    {
        $user_id = $this->auth->id;

        //获取json数据 {"1":150,"3":200} -> {"服务id”:“价格”}
        $input = file_get_contents('php://input');
        $data = json_decode($input,true);

        $expertInfo = db('expert')->where(['user_id' => $user_id])->field('id,money')->find();
        if (!$expertInfo){
            $this->error('参数错误!');
        }

        if ($data && is_array($data)){

            foreach ($data as $key => $value){

                $service_id = $key;
                $price = $value;

                if (!$service_id || !is_numeric($price)){
                    $this->error('参数错误!');
                }
                $expertService = db('expert_service')->where(['user_id' => $user_id, 'service_id' => $service_id])->find();
                if ($expertService){
                    $res = db('expert_service')->where(['user_id' => $user_id, 'service_id' => $service_id])->update(['price' => $price ,'updatetime' => time()]);
                }else{
                    $data = [
                        'expert_id'=>$expertInfo['id'],
                        'user_id'=>$user_id,
                        'service_id'=>$service_id,
                        'price'=>$price,
                        'createtime'=>time(),
                        'updatetime' => time()
                    ];

                    $res = db('expert_service')->insert($data);
                }
                if (!$res){
                    $this->error('系统执行异常!');
                }
            }
        }

        $this->success('ok');

    }

    public function getPlaymateServiceTime()
    {
        $user_id = 3;
        $expertInfo = db('expert')->where(['user_id' => $user_id])->field('id,start_time,end_time,order_status')->find();
        if(empty($expertInfo)){
            $this->error('您暂时不是达人');
        }
        if(empty($expertInfo['start_time'])){
            $expertInfo['start_time'] = '09:00:00';
        }
        if(empty($expertInfo['end_time'])){
            $expertInfo['end_time'] = '23:30:00';
        }
        //去掉最后三位数
        $expertInfo['start_time'] = substr($expertInfo['start_time'], 0, -3);
        $expertInfo['end_time'] = substr($expertInfo['end_time'], 0, -3);
        $service_time = db('expert_service_time')->where('expert_id',$expertInfo['id'])->where('date','>=',date('Y-m-d'))->field('date,time,cannot_time')->column('date,time,cannot_time','date');
        foreach ($service_time as &$v){
            $v['time'] = json_decode($v['time'],true);
            $v['cannot_time'] = json_decode($v['cannot_time'],true);
        }

        //循坏出7天的日期
        $date_arr = [];
        for($i=0;$i<7;$i++){
            $time_arr = [];
            $cannot_time = [];
            $date = date('Y-m-d',strtotime("+$i day"));
            if(isset($service_time[$date])){
                $time_arr = $service_time[$date]['time'];
                $cannot_time = $service_time[$date]['cannot_time'];
            }else{
                $start_time_s = strtotime($date." ".$expertInfo['start_time']);
                $end_time_s = strtotime($date." ".$expertInfo['end_time']);

                for ($i1 = $start_time_s; $i1 <= $end_time_s; $i1 += 1800){
                    $time_arr[] = date("H:i",$i1);
                }
            }
            $date_arr[] = [
                'date'=>$date,
                'time'=>$time_arr,
                'cannot_time'=>$cannot_time,
            ];
        }

        $this->success('成功',['expertInfo'=>$expertInfo,'service_time'=>$date_arr]);

    }

    /**
     * 达人 设置服务时间
     * @param string start_time Y 接单开始时间
     * @param string end_time Y 接单结束时间
     * @param string cannot_time Y 不接单时间
     * @param string date Y 日期
     */
    public function setPlaymateServiceTime()
    {
        $user_id = 3;
        $data = $this->request->post();
        $start_time = $this->request->post('start_time');
        $end_time = $this->request->post('end_time');
        $order_status = $this->request->post('order_status');
        $service_time = $data['service_time'];
        if($order_status == 1){
            if(empty($service_time)){
                $this->error('请设置服务时间');
            }
        }
        $expertInfo = db('expert')->where(['user_id' => $user_id])->field('id,start_time,end_time,order_status')->find();
        if(empty($expertInfo)){
            $this->error('您暂时不是达人');
        }
        foreach ($service_time as &$value){
            if(empty($value['date'])){
                $this->error('请设置服务日期');
            }
            //将时间切割为半小时一个
            $start_time_s = strtotime($value['date']." ".$start_time);
            $end_time_s = strtotime($value['date']." ".$end_time);
            $time_arr = [];
            for ($i = $start_time_s; $i <= $end_time_s; $i += 1800){
                $time_arr[] = date("H:i",$i);
            }
            //排除不接单时间点
            $time = array_merge(array_diff($time_arr, $value['cannot_time']) , array_diff($value['cannot_time'], $time_arr));
            $value['expert_id'] = $expertInfo['id'];
            $value['user_id'] = $user_id;
            $value['createtime'] = time();
            $value['time'] = json_encode($time);
            $value['cannot_time'] = json_encode($value['cannot_time']);

        }
        unset($value);
        Db::startTrans();
        try {
            foreach ($service_time as $value){
                $expertService = db('expert_service_time')->where(['user_id' => $user_id, 'date' => $value['date']])->find();
                if ($expertService){
                    $value['updatetime'] = time();
                    $res = db('expert_service_time')->where(['id' => $expertService['id']])->update($value);
                }else{
                    $value['createtime'] = time();
                    $value['updatetime'] = time();
                    $res = db('expert_service_time')->insert($value);
                }
            }

            Db::commit();
        } catch (Exception $e) {
            //print_r($e->getMessage());
            Db::rollback();
            $this->error('系统执行异常!');
        }
        $this->success('设置成功');
















        $start_time = $this->request->post('start_time');
        $end_time = $this->request->post('end_time');
        $cannot_time = $this->request->post('cannot_time');
        $date = $this->request->post('date');

        if (!$start_time || !$end_time || !$date){
            $this->error('参数错误!');
        }

        //查询达人
        $expertInfo = db('expert')->where(['user_id' => $user_id])->field('id')->find();

        //将时间切割为半小时一个
        $start_time_s = strtotime($date." ".$start_time);
        $end_time_s = strtotime($date." ".$end_time);
        $time_arr = [];
        for ($i = $start_time_s; $i <= $end_time_s; $i += 1800){
            $time_arr[] = date("H:i",$i);
        }

        //不接单时间点
        $cannot_time_arr = [];
        if ($cannot_time){
            $cannot_time_arr = explode(',',$cannot_time);
        }

        //排除不接单时间点
        $accept_time = array_merge(array_diff($time_arr, $cannot_time_arr) , array_diff($cannot_time_arr, $time_arr));

        //写入数据
        $data = [
            'expert_id' => $expertInfo['id'],
            'user_id' => $user_id,
            'date' => $date,
            'time' => json_encode($accept_time),
            'cannot_time' => json_encode($cannot_time_arr),
        ];


        $expertService = db('expert_service_time')->where(['user_id' => $user_id, 'date' => $date])->find();
        if ($expertService){
            $data['updatetime'] = time();
            $res = db('expert_service_time')->where(['id' => $expertService['id']])->update($data);
        }else{
            $data['createtime'] = time();
            $res = db('expert_service_time')->insert($data);
        }
        if (!$res){
            $this->error('系统执行异常!');
        }
        $this->success('ok');

    }


    /**
     * 金额明细列表
     *
     * @ApiMethod (POST)
     * @ApiParams (name="page", type="string", required=false, description="分页页码, 默认1")
     * @ApiParams (name="limit", type="string", required=false, description="分页, 每页数据条数, 默认10")
     * @ApiParams (name="type", type="string", required=true, description="分类")
     */
    public function getPlaymateMoneyLog()
    {
        $user = $this->auth->getUser();
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);
        $type = $this->request->post('type', '1');
        $model = new ExpertMoneyLog();
        if ($type !== '') {
            $model = $model->where('type', $type);
        }
        $model = $model->where('user_id', $user['id']);
        $data = $model
            ->with(['serviceDetail', 'serviceDetail.service','fromuserDetail',])
            ->page($page, $limit)->order('createtime', 'desc')
            ->select();

        foreach ($data as &$v){

            $v['fromuser_name'] = $v['service_name'] = $v['service_num'] = '';
            if (isset($v['service_detail']['service']) && $v['service_detail']['service']){
                $v['service_name'] = $v['service_detail']['service']['name'];
                $v['service_num'] = $v['service_detail']['num'];
            }
            if (isset($v['fromuser_detail']['nickname']) && $v['fromuser_detail']['nickname']){
                $v['fromuser_name'] = $v['fromuser_detail']['nickname'];
            }
            unset($v['service_detail']);
            unset($v['fromuser_detail']);

        }

        $this->success(__('Operation completed'), $data);
    }




}
